#!/usr/bin/env bash
# ******************************************************
# Filename     : dns_centos8_install.sh
# Last modified: 2022-10-11 12:18
# Version      :
# AppVersion   : 32:9.11.36-5.el8
# Author       : jack.zang
# Email        : jack_zang@126.com
# Description  : 部署前，请修改 DOMAIN HOSTIP REVERSE_LOOKUP_ADDR
# source <(curl -sL https://gitee.com/jack_zang/public-scripts/raw/master/shell/dns/dns_centos8_install.sh)
# Add DNS Resolution: echo "www A 192.168.10.237" >> /var/named/xiodi.cn.zone && rndc reload
#
# ******************************************************

DOMAIN="xiodi.cn"
HOSTIP="192.168.10.219"
REVERSE_LOOKUP_ADDR="10.168.192"

yum -y install bind

cat > /etc/named.conf <<EOF
options {
	  listen-on port 53 { any; };  // DNS 服务侦听地址和端口
	  listen-on-v6 port 53 { ::1; };
	  directory 	"/var/named";
	  dump-file 	"/var/named/data/cache_dump.db";
	  statistics-file "/var/named/data/named_stats.txt";
	  memstatistics-file "/var/named/data/named_mem_stats.txt";
	  secroots-file	"/var/named/data/named.secroots";
	  recursing-file	"/var/named/data/named.recursing";
	  allow-query     { any; };  // 允许查询的主机
	  recursion yes;
	  dnssec-enable yes;
	  dnssec-validation no;   // 禁用 dns 检测，使 dns 能够缓存外部信息到本机
	  managed-keys-directory "/var/named/dynamic";
	  pid-file "/run/named/named.pid";
	  session-keyfile "/run/named/session.key";
	  include "/etc/crypto-policies/back-ends/bind.config";
};
logging {
    channel default_debug {
        file "data/named.run";
        severity dynamic;
    };
};
zone "." IN {
	  type hint;
	  file "named.ca";
};
include "/etc/named.rfc1912.zones";  // 该文件存放维护的域
include "/etc/named.root.key";
EOF

### DNS 正向解析
cat >> /etc/named.rfc1912.zones <<EOF
zone "$DOMAIN" IN {
    type master;
    file "${DOMAIN}.zone";
    allow-update { none; };
};
EOF

cat > /var/named/${DOMAIN}.zone <<EOF
\$TTL 1D
@	    IN   SOA	  dns.${DOMAIN}. root.${DOMAIN}. ( 0 1D 1H 1W 3H )
@          NS   dns.${DOMAIN}.
dns        A    ${HOSTIP}
test       A    1.1.1.11
EOF

systemctl enable named && systemctl start named

### DNS 反向解析，一般用不上

cat >> /etc/named.rfc1912.zones <<EOF
zone "${REVERSE_LOOKUP_ADDR}.in-addr.arpa" IN {
    type master;
    file "${REVERSE_LOOKUP_ADDR}.ptr";
    allow-update { none; };
};
EOF

cat > /var/named/${REVERSE_LOOKUP_ADDR}.ptr <<EOF
\$TTL  1D
@	    IN   SOA	  dns.${DOMAIN}. root.${DOMAIN}. ( 0 1D 1H 1W 3H )
@          NS   dns.${DOMAIN}.
dns        A    ${HOSTIP}
10         PTR  test.${DOMAIN}
EOF

systemctl restart named

### 验证
# yum -y install bind-utils
# dig test.xiodi.cn
# dig 192.168.10.10   # 根据反向解析的地址不同而不同，比如 10.168.192 ，上面的 10